package com.atguigu.service.impl;

import com.atguigu.annotations.MyRedisCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * @author -GRW
 * @description 针对表【t_user(用户表)】的数据库操作Service实现
 * @createDate 2025-07-31 10:56:12
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    public static final String CACHE_KEY_USER = "user:";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean save(User entity) {
        boolean retValue = false;
        log.info("插入之前user:{}", user);
        retValue = super.save(entity);//插入数据
        log.info("插入之后user:{}", user);
        if (retValue) {
            log.info("插入成功");
            entity = this.userMapper.selectById(entity.getId());// 查询插入数据
            String key = CACHE_KEY_USER + entity.getId();// 缓存的key
            redisTemplate.opsForValue().set(key, entity);// 缓存数据
        }
        return retValue;
    }
    @MyRedisCache(keyPrefix = "user", matchValue = "#id")
    @Override
    public User getById(Serializable id) {
        return this.userMapper.selectById(id);
    }
}




